<template>
  <div class="payment-fail-page">
    <div class="container">
      <div class="fail-content">
        <!-- 失败图标 -->
        <div class="fail-icon">
          <el-icon :size="80" color="#f56c6c">
            <CircleCloseFilled />
          </el-icon>
        </div>

        <!-- 失败信息 -->
        <div class="fail-info">
          <h1>支付失败</h1>
          <p class="fail-desc">很抱歉，订单支付未能完成</p>
          <div class="fail-reason" v-if="failReason">
            <el-icon><WarningFilled /></el-icon>
            <span>失败原因：{{ failReason }}</span>
          </div>
        </div>

        <!-- 订单信息 -->
        <el-card class="order-summary-card" v-if="orderInfo">
          <div class="order-summary">
            <div class="order-header">
              <span class="label">订单号</span>
              <span class="value">{{ orderInfo.orderNumber }}</span>
            </div>
            <div class="order-detail">
              <span class="label">应付金额</span>
              <span class="amount">¥{{ orderInfo.totalAmount }}</span>
            </div>
            <div class="order-detail">
              <span class="label">订单状态</span>
              <el-tag type="warning" size="small">待支付</el-tag>
            </div>
            <div class="order-detail">
              <span class="label">创建时间</span>
              <span class="value">{{ formatDateTime(orderInfo.createdAt) }}</span>
            </div>
          </div>
        </el-card>

        <!-- 失败原因详细说明 -->
        <el-card class="reason-card" v-if="failureDetails">
          <template #header>
            <h3>
              <el-icon><InfoFilled /></el-icon>
              失败详情
            </h3>
          </template>
          <div class="reason-content">
            <div class="reason-item">
              <span class="reason-label">错误代码：</span>
              <span class="reason-value">{{ failureDetails.errorCode }}</span>
            </div>
            <div class="reason-item">
              <span class="reason-label">详细说明：</span>
              <span class="reason-value">{{ failureDetails.description }}</span>
            </div>
            <div class="reason-item" v-if="failureDetails.suggestion">
              <span class="reason-label">建议处理：</span>
              <span class="reason-value">{{ failureDetails.suggestion }}</span>
            </div>
          </div>
        </el-card>

        <!-- 解决方案 -->
        <el-card class="solutions-card">
          <template #header>
            <h3>
              <el-icon><Tools /></el-icon>
              解决方案
            </h3>
          </template>
          <div class="solutions-content">
            <div class="solution-item" v-for="solution in solutions" :key="solution.id">
              <div class="solution-icon">
                <el-icon :color="solution.color">
                  <component :is="solution.icon" />
                </el-icon>
              </div>
              <div class="solution-info">
                <h4>{{ solution.title }}</h4>
                <p>{{ solution.description }}</p>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button 
            type="primary" 
            size="large"
            @click="retryPayment"
            :loading="retrying"
            :icon="Refresh"
          >
            重新支付
          </el-button>
          
          <el-button 
            size="large"
            @click="changePaymentMethod"
            :icon="CreditCard"
          >
            更换支付方式
          </el-button>
          
          <el-button 
            size="large"
            @click="contactService"
            :icon="Service"
          >
            联系客服
          </el-button>
          
          <el-button 
            size="large"
            @click="cancelOrder"
            :icon="Close"
          >
            取消订单
          </el-button>
        </div>

        <!-- 帮助信息 -->
        <div class="help-section">
          <h4>需要帮助？</h4>
          <div class="help-options">
            <div class="help-item" @click="openHelp('payment')">
              <el-icon><QuestionFilled /></el-icon>
              <span>支付问题</span>
            </div>
            <div class="help-item" @click="openHelp('refund')">
              <el-icon><Money /></el-icon>
              <span>退款政策</span>
            </div>
            <div class="help-item" @click="contactOnlineService">
              <el-icon><ChatDotRound /></el-icon>
              <span>在线客服</span>
            </div>
          </div>
        </div>

        <!-- 其他订单推荐 -->
        <div class="other-orders" v-if="otherOrders.length > 0">
          <h4>您可能还需要</h4>
          <div class="order-grid">
            <div 
              v-for="order in otherOrders" 
              :key="order.id"
              class="order-card"
              @click="goToService(order.serviceId)"
            >
              <div class="order-image">
                <el-image :src="order.image" fit="cover" class="image" />
              </div>
              <div class="order-info">
                <h5>{{ order.name }}</h5>
                <p class="order-price">¥{{ order.price }}/{{ order.unit }}</p>
                <el-tag size="small" type="success">{{ order.discount }}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 客服对话框 -->
    <el-dialog v-model="showServiceDialog" title="联系客服" width="400px">
      <div class="service-options">
        <div class="service-item" @click="callService">
          <el-icon size="24"><Phone /></el-icon>
          <div class="service-info">
            <h4>电话客服</h4>
            <p>400-123-4567</p>
            <span class="service-time">服务时间：9:00-21:00</span>
          </div>
        </div>
        
        <div class="service-item" @click="startOnlineChat">
          <el-icon size="24"><ChatDotRound /></el-icon>
          <div class="service-info">
            <h4>在线客服</h4>
            <p>即时回复，随时为您服务</p>
            <span class="service-time">24小时在线</span>
          </div>
        </div>
        
        <div class="service-item" @click="sendEmail">
          <el-icon size="24"><Message /></el-icon>
          <div class="service-info">
            <h4>邮件反馈</h4>
            <p>service@laundry.com</p>
            <span class="service-time">1个工作日内回复</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  CircleCloseFilled,
  WarningFilled,
  InfoFilled,
  Tools,
  Refresh,
  CreditCard,
  Service,
  Close,
  QuestionFilled,
  Money,
  ChatDotRound,
  Phone,
  Message,
  Wallet,
  Setting,
  Connection
} from '@element-plus/icons-vue'
import { orderApi, serviceApi } from '@/services/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 数据定义
const orderInfo = ref(null)
const failReason = ref('')
const failureDetails = ref(null)
const otherOrders = ref([])
const retrying = ref(false)
const showServiceDialog = ref(false)

// 解决方案列表
const solutions = ref([
  {
    id: 1,
    icon: CreditCard,
    color: '#409eff',
    title: '检查支付方式',
    description: '确认银行卡余额充足，或尝试其他支付方式'
  },
  {
    id: 2,
    icon: Connection,
    color: '#67c23a',
    title: '检查网络连接',
    description: '确保网络连接稳定，重新尝试支付'
  },
  {
    id: 3,
    icon: Setting,
    color: '#e6a23c',
    title: '检查支付设置',
    description: '确认支付应用版本最新，支付功能已开启'
  },
  {
    id: 4,
    icon: Service,
    color: '#f56c6c',
    title: '联系客服',
    description: '如问题持续存在，请联系客服获取帮助'
  }
])

// 生命周期
onMounted(() => {
  const orderId = route.query.orderId || route.params.orderId
  const reason = route.query.reason || '支付过程中发生错误'
  const errorCode = route.query.errorCode
  
  failReason.value = reason
  
  if (errorCode) {
    failureDetails.value = getFailureDetails(errorCode)
  }
  
  if (orderId) {
    fetchOrderInfo(orderId)
  }
  
  fetchOtherOrders()
})

// 方法定义
const fetchOrderInfo = async (orderId) => {
  try {
    const response = await orderApi.getOrderDetail(orderId)
    orderInfo.value = response.data
  } catch (error) {
    console.error('获取订单信息失败:', error)
    
    // 使用模拟数据
    orderInfo.value = {
      id: orderId,
      orderNumber: `202412280${orderId.toString().padStart(3, '0')}`,
      totalAmount: 65,
      status: 'pending',
      createdAt: new Date(Date.now() - 300000), // 5分钟前
      service: {
        id: 1,
        name: '高档衣物干洗'
      }
    }
  }
}

const fetchOtherOrders = async () => {
  try {
    const response = await serviceApi.getPopularServices()
    otherOrders.value = response.data || []
  } catch (error) {
    console.error('获取推荐服务失败:', error)
    
    // 使用模拟数据
    otherOrders.value = [
      {
        id: 2,
        serviceId: 2,
        name: '普通洗衣服务',
        price: 15,
        unit: '件',
        image: '/default-service.jpg',
        discount: '限时8折'
      },
      {
        id: 3,
        serviceId: 3,
        name: '鞋类清洗护理',
        price: 25,
        unit: '双',
        image: '/default-service.jpg',
        discount: '新用户专享'
      }
    ]
  }
}

const getFailureDetails = (errorCode) => {
  const errorMap = {
    'INSUFFICIENT_BALANCE': {
      errorCode: 'INSUFFICIENT_BALANCE',
      description: '账户余额不足，无法完成支付',
      suggestion: '请充值后重新尝试，或选择其他支付方式'
    },
    'NETWORK_ERROR': {
      errorCode: 'NETWORK_ERROR',
      description: '网络连接超时或不稳定',
      suggestion: '请检查网络连接后重新尝试'
    },
    'PAYMENT_DECLINED': {
      errorCode: 'PAYMENT_DECLINED',
      description: '银行拒绝了此次交易',
      suggestion: '请联系您的银行确认卡片状态'
    },
    'SYSTEM_ERROR': {
      errorCode: 'SYSTEM_ERROR',
      description: '支付系统暂时不可用',
      suggestion: '请稍后重试或联系客服'
    }
  }
  
  return errorMap[errorCode] || {
    errorCode: errorCode || 'UNKNOWN_ERROR',
    description: '未知错误，支付过程中发生异常',
    suggestion: '请重新尝试或联系客服获取帮助'
  }
}

const retryPayment = () => {
  if (orderInfo.value) {
    retrying.value = true
    // 模拟重新支付过程
    setTimeout(() => {
      retrying.value = false
      router.push(`/payment/${orderInfo.value.id}`)
    }, 1000)
  }
}

const changePaymentMethod = () => {
  if (orderInfo.value) {
    router.push(`/payment/${orderInfo.value.id}?changeMethod=true`)
  }
}

const contactService = () => {
  showServiceDialog.value = true
}

const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个订单吗？取消后无法恢复。',
      '取消订单',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '我再想想',
        type: 'warning'
      }
    )

    if (orderInfo.value) {
      await orderApi.cancelOrder(orderInfo.value.id)
      ElMessage.success('订单已取消')
      router.push('/orders')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

const openHelp = (type) => {
  const helpMap = {
    payment: '/help/payment',
    refund: '/help/refund'
  }
  router.push(helpMap[type] || '/help')
}

const contactOnlineService = () => {
  router.push('/chat/service')
}

const goToService = (serviceId) => {
  router.push(`/services/${serviceId}`)
}

const callService = () => {
  window.open('tel:400-123-4567')
  showServiceDialog.value = false
}

const startOnlineChat = () => {
  showServiceDialog.value = false
  router.push('/chat/service')
}

const sendEmail = () => {
  window.open('mailto:service@laundry.com')
  showServiceDialog.value = false
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.payment-fail-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f56c6c 0%, #e85a4f 100%);
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.fail-content {
  text-align: center;
}

.fail-icon {
  margin-bottom: 20px;
  animation: failShake 0.8s ease-out;
}

@keyframes failShake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.fail-info {
  color: white;
  margin-bottom: 30px;

  h1 {
    font-size: 32px;
    font-weight: 700;
    margin: 0 0 12px 0;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  .fail-desc {
    font-size: 18px;
    margin: 0 0 16px 0;
    opacity: 0.9;
  }

  .fail-reason {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: rgba(255, 255, 255, 0.2);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    backdrop-filter: blur(10px);
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  text-align: left;
}

.order-summary-card {
  .order-summary {
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 16px;

      .label {
        font-weight: 500;
        color: #666;
      }

      .value {
        font-weight: 600;
        color: #333;
        font-size: 16px;
      }
    }

    .order-detail {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .label {
        color: #666;
        font-size: 14px;
      }

      .value {
        color: #333;
        font-size: 14px;
      }

      .amount {
        color: #e6a23c;
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
}

.reason-card {
  .el-card__header h3 {
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    color: #333;
  }

  .reason-content {
    .reason-item {
      display: flex;
      margin-bottom: 12px;

      .reason-label {
        color: #666;
        font-size: 14px;
        min-width: 80px;
      }

      .reason-value {
        color: #333;
        font-size: 14px;
        flex: 1;
      }
    }
  }
}

.solutions-card {
  .el-card__header h3 {
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    color: #333;
  }

  .solutions-content {
    .solution-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      margin-bottom: 16px;
      padding: 12px;
      background: #f8f9fa;
      border-radius: 8px;

      .solution-icon {
        flex-shrink: 0;
        margin-top: 2px;
      }

      .solution-info {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
          color: #333;
        }

        p {
          margin: 0;
          font-size: 12px;
          color: #666;
          line-height: 1.4;
        }
      }
    }
  }
}

.action-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin: 30px 0;

  .el-button {
    height: 48px;
    font-size: 14px;
    border-radius: 8px;
  }
}

.help-section {
  margin: 30px 0;

  h4 {
    color: white;
    margin-bottom: 16px;
    font-size: 18px;
  }

  .help-options {
    display: flex;
    justify-content: center;
    gap: 20px;

    .help-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      padding: 16px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.3s ease;
      backdrop-filter: blur(10px);
      color: white;

      &:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: translateY(-2px);
      }

      span {
        font-size: 12px;
      }
    }
  }
}

.other-orders {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin-top: 20px;

  h4 {
    margin: 0 0 16px 0;
    font-size: 16px;
    color: #333;
    text-align: center;
  }

  .order-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
  }

  .order-card {
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
    }

    .order-image {
      width: 100%;
      height: 80px;
      border-radius: 6px;
      overflow: hidden;
      margin-bottom: 8px;

      .image {
        width: 100%;
        height: 100%;
      }
    }

    .order-info {
      h5 {
        margin: 0 0 4px 0;
        font-size: 14px;
        color: #333;
        line-height: 1.4;
      }

      .order-price {
        margin: 0 0 4px 0;
        color: #e6a23c;
        font-weight: 600;
        font-size: 14px;
      }
    }
  }
}

.service-options {
  .service-item {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    margin-bottom: 12px;

    &:hover {
      background-color: #f5f7fa;
    }

    .service-info {
      flex: 1;

      h4 {
        margin: 0 0 4px 0;
        font-size: 16px;
        color: #333;
      }

      p {
        margin: 0 0 4px 0;
        color: #666;
        font-size: 14px;
      }

      .service-time {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .fail-info h1 {
    font-size: 28px;
  }

  .action-buttons {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .help-options {
    flex-direction: column;
    gap: 12px;

    .help-item {
      flex-direction: row;
      justify-content: center;
      padding: 12px 16px;
    }
  }

  .other-orders .order-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}
</style> 